﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AutoMapper;

namespace AutoMapperSamples.Samples.CustomValRes
{
    [TestClass]
    public class CustomValResolvers
    {
        [TestMethod]
        public void CustomValResTest()
        {
            //初始化映射规则，并调用 CustomResolver自定义解析
            Mapper.Initialize(cfg =>
            cfg.CreateMap<Source, Destination>()
            .ForMember(dest => dest.Total, opt => opt.ResolveUsing<CustomResolver>()));
            Mapper.AssertConfigurationIsValid();
            var source = new Source
            {
                Value1 = 5,
                Value2 = 7
            };
            var result = Mapper.Map<Source, Destination>(source);
            Assert.AreEqual(12,result.Total);
        }

        [TestMethod]
        public void CustomValResV2Test()
        {
            //初始化映射规则，
            Mapper.Initialize(cfg =>
            cfg.CreateMap<Source, Destination>()
            .ForMember(dest => dest.Total, opt => opt.ResolveUsing<CustomResolverV2,int>(src=>src.Value1)));
            //Mapper.AssertConfigurationIsValid();
            var source = new Source
            {
                Value1 = 5,
                //Value2 = 7
            };
            var result = Mapper.Map<Source, Destination>(source);
            Assert.AreEqual(10, result.Total);
        }
    }
    /// <summary>
    /// 自定义解析类
    /// </summary>
    public class CustomResolver : IValueResolver<Source, Destination, int>
    {
        /// <summary>
        /// 自定义解析实现
        /// </summary>
        /// <param name="source">源对象</param>
        /// <param name="destination">目标对象</param>
        /// <param name="member">目标对象的值</param>
        /// <param name="context"></param>
        /// <returns></returns>
        public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
        {
            return source.Value1 + source.Value2;
        }
    }

    /// <summary>
    /// 自定义解析类V2 根据源对象的源映射值解析
    /// </summary>
    public class CustomResolverV2 : IMemberValueResolver<object, object, int, int>
    {
        public int Resolve(object source, object destination, int sourceMember, int destinationMember, ResolutionContext context)
        {
            return sourceMember * 2;
            // logic here
        }
    }

    public class Source
    {
        public int Value1 { get; set; }
        public int Value2 { get; set; }
    }

    public class Destination
    {
        public int Total { get; set; }
    }
}
